<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\SystemSetting;
use Illuminate\Support\Facades\Cache;

class SyncSystemSettings extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'system:sync-settings {--clear-cache : 清除所有缓存}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步系统设置到Laravel配置系统';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('开始同步系统设置...');

        try {
            // 如果指定了清除缓存选项
            if ($this->option('clear-cache')) {
                $this->info('清除所有缓存...');
                Cache::flush();
                $this->info('缓存已清除');
            }

            // 重新加载配置
            SystemSetting::reloadConfigs();
            
            // 获取设置数量
            $settingsCount = SystemSetting::count();
            
            $this->info("成功同步 {$settingsCount} 个系统设置到Laravel配置系统");
            
            // 显示一些关键设置
            $this->displayKeySettings();
            
            $this->info('系统设置同步完成！');
            
        } catch (\Exception $e) {
            $this->error('同步系统设置时发生错误: ' . $e->getMessage());
            return 1;
        }

        return 0;
    }

    /**
     * 显示关键设置信息
     */
    private function displayKeySettings()
    {
        $this->info('关键设置信息:');
        
        $keySettings = [
            'app_name' => '应用名称',
            'site_name' => '站点名称',
            'site_description' => '站点描述',
            'maintenance_mode' => '维护模式',
            'mail_host' => '邮件主机',
            'mail_port' => '邮件端口',
        ];

        $table = [];
        foreach ($keySettings as $key => $label) {
            $value = SystemSetting::get($key, '未设置');
            if (is_bool($value)) {
                $value = $value ? '是' : '否';
            }
            $table[] = [$label, $key, $value];
        }

        $this->table(['设置名称', '键名', '当前值'], $table);
    }
}